<template>
  <div class="address-container">
    <div class="address-header">
      <h2>收货地址管理</h2>
      <el-button type="primary" @click="openAddressDialog()">
        <el-icon><plus /></el-icon> 新增收货地址
      </el-button>
    </div>

    <div v-if="addressList.length === 0" class="empty-address">
      <el-empty description="暂无收货地址" />
    </div>

    <div v-else class="address-list">
      <el-card v-for="address in addressList" :key="address.id" class="address-card">
        <div class="address-card-header">
          <div class="address-info">
            <span class="address-name">{{ address.name }}</span>
            <span class="address-phone">{{ address.phone }}</span>
            <el-tag v-if="address.isDefault == 1" type="success" size="small" class="default-tag">默认地址</el-tag>
          </div>
          <div class="address-actions">
            <el-button type="primary" link @click="openAddressDialog(address)">编辑</el-button>
            <el-button type="danger" link @click="deleteAddress(address.id)">删除</el-button>
          </div>
        </div>

        <div class="address-card-body">
          <p class="address-detail">
            <span class="address-region">{{ address.province }} {{ address.city }} {{ address.district }}</span>
            <span class="address-street">{{ address.detail }}</span>
          </p>
        </div>

        <div v-if="address.isDefault != 1" class="address-card-footer">
          <el-button type="primary" link @click="setDefaultAddress(address.id)">设为默认地址</el-button>
        </div>
      </el-card>
    </div>

    <!-- 地址编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form :model="addressForm" :rules="rules" ref="addressFormRef" label-width="100px">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addressForm.name" placeholder="请输入收货人姓名" />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码" />
        </el-form-item>

        <el-form-item label="所在地区">
          <el-cascader
            v-model="selectedRegion"
            :options="regions"
            :props="{ expandTrigger: 'hover' }"
            placeholder="请选择省/市/区"
            style="width: 100%"
            @change="handleRegionChange"
          />
        </el-form-item>

        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="addressForm.detail" type="textarea" placeholder="请输入详细地址" />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault" :true-label="1" :false-label="0">设为默认收货地址</el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { getAddresses, addAddress, updateAddress, deleteAddress as deleteAddressApi } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { regions } from '@/data/regions'

// 地址列表
const addressList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = computed(() => addressForm.value.id ? '编辑收货地址' : '新增收货地址')
const addressFormRef = ref<FormInstance>()

// 地址表单
const addressForm = ref({
  id: null,
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: 0
})

// 级联选择器选中的地区
const selectedRegion = ref<string[]>([])

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ]
}

// 处理地区选择变化
const handleRegionChange = (value: string[]) => {
  if (value && value.length === 3) {
    addressForm.value.province = value[0]
    addressForm.value.city = value[1]
    addressForm.value.district = value[2]
  }
}

// 获取地址列表
const getAddressList = async () => {
  try {
    const response = await getAddresses()
    if (response.code === 200) {
      addressList.value = response.data
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  }
}

// 打开地址对话框
const openAddressDialog = (address = null) => {
  if (address) {
    // 编辑地址 - 直接设置表单数据，不重置
    addressForm.value = { ...address }
    // 设置级联选择器的值
    selectedRegion.value = [
      address.province,
      address.city,
      address.district
    ]
  } else {
    // 新增地址 - 重置表单
    resetAddressForm()
  }

  dialogVisible.value = true
}

// 重置地址表单
const resetAddressForm = () => {
  addressForm.value = {
    id: null,
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: '',
    isDefault: 0
  }

  // 重置级联选择器
  selectedRegion.value = []

  if (addressFormRef.value) {
    addressFormRef.value.resetFields()
  }
}

// 保存地址
const saveAddress = async () => {
  if (!addressFormRef.value) return

  // 检查是否选择了地区
  if (!selectedRegion.value || selectedRegion.value.length !== 3) {
    ElMessage.warning('请选择完整的省市区信息')
    return
  }

  // 确保地区信息已经同步到表单
  handleRegionChange(selectedRegion.value)

  await addressFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (addressForm.value.id) {
          // 更新地址 - 只发送AddressParam中定义的字段
          const updateData = {
            name: addressForm.value.name,
            phone: addressForm.value.phone,
            province: addressForm.value.province,
            city: addressForm.value.city,
            district: addressForm.value.district,
            detail: addressForm.value.detail,
            isDefault: addressForm.value.isDefault
          }
          const response = await updateAddress(addressForm.value.id, updateData)
          if (response.code === 200) {
            ElMessage.success('更新地址成功')
            dialogVisible.value = false
            getAddressList()
          }
        } else {
          // 添加地址 - 只发送AddressParam中定义的字段
          const addData = {
            name: addressForm.value.name,
            phone: addressForm.value.phone,
            province: addressForm.value.province,
            city: addressForm.value.city,
            district: addressForm.value.district,
            detail: addressForm.value.detail,
            isDefault: addressForm.value.isDefault
          }
          const response = await addAddress(addData)
          if (response.code === 200) {
            ElMessage.success('添加地址成功')
            dialogVisible.value = false
            getAddressList()
          }
        }
      } catch (error) {
        console.error('保存地址失败:', error)
        ElMessage.error('保存地址失败')
      }
    } else {
      return false
    }
  })
}

// 删除地址
const deleteAddress = (id) => {
  ElMessageBox.confirm('确定要删除这个地址吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteAddressApi(id)
      if (response.code === 200) {
        ElMessage.success('删除地址成功')
        getAddressList()
      }
    } catch (error) {
      console.error('删除地址失败:', error)
      ElMessage.error('删除地址失败')
    }
  }).catch(() => {})
}

// 设置默认地址
const setDefaultAddress = async (id) => {
  try {
    const address = addressList.value.find(item => item.id === id)
    if (address) {
      // 直接设置新的默认地址，后端会自动处理重置其他地址
      const updateData = {
        name: address.name,
        phone: address.phone,
        province: address.province,
        city: address.city,
        district: address.district,
        detail: address.detail,
        isDefault: 1
      }
      const response = await updateAddress(id, updateData)
      if (response.code === 200) {
        ElMessage.success('设置默认地址成功')
        // 重新获取数据确保同步
        await getAddressList()
      }
    }
  } catch (error) {
    console.error('设置默认地址失败:', error)
    ElMessage.error('设置默认地址失败')
  }
}

// 页面加载时获取地址列表
onMounted(() => {
  getAddressList()
})
</script>

<style scoped>
.address-container {
  padding: 20px 0;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.address-header h2 {
  margin: 0;
  color: #333;
}

.empty-address {
  margin: 50px 0;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.el-card.address-card :deep(.el-card__body) {
  padding: 15px;
}

.address-card {
  height: 100%;
  min-height: 160px;
  display: flex;
  flex-direction: column;
  position: relative;
}

.address-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.address-info {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  max-width: 70%;
}

.address-actions {
  min-width: 80px;
  text-align: right;
}

.address-name {
  font-weight: bold;
  font-size: 16px;
}

.address-card-body {
  flex: 1;
  margin-bottom: 40px; /* 为底部留出空间 */
}

.address-detail {
  color: #666;
  line-height: 1.5;
  word-break: break-all;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.address-region {
  font-weight: 500;
}

.address-street {
  color: #909399;
}

.address-card-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 20px;
  border-top: 1px solid #eee;
  background-color: #fff;
}

.no-label :deep(.el-form-item__label) {
  display: none;
}

.default-tag {
  margin-left: 5px;
}

/* 级联选择器样式 */
:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-cascader__dropdown) {
  min-width: 160px !important;
}

:deep(.el-cascader-panel) {
  min-width: 160px;
}
</style>
